<?php

declare(strict_types=1);

/**
 * @Author:     Frank
 * @contact     frank_hhm@163.com
 * @Date:       2023-02-06 20:47:10
 * @Last Modified time: 2023-02-22 15:55:03
 */
namespace app\common\model\store;

use frank\base\BaseModel;
use frank\traits\ModelTrait;
use app\common\enum\EnumFactory;
use app\common\enum\store\order\SourceEnum;
use app\common\enum\store\order\StatusEnum;
use app\common\enum\store\order\DeliveryStatusEnum;
use app\common\enum\store\DeliveryTypeEnum;
use think\model\concern\SoftDelete;

/**
 * 订单
 * Class OrderModel
 * @package app\common\model\store
 */
class OrderModel extends BaseModel
{
    use ModelTrait;
    use SoftDelete;

    /**
     * 数据表主键
     */
    protected $pk = 'id';

    /**
     * 模型名称
     */
    protected $name = 'store_order';

    protected $deleteTime = 'delete_time';

    protected $defaultSoftDelete = 0;

    /**
     * 追加字段
     * @var array
     */
    protected $append = [
        'status_text',      // 状态文字描述
        'invalid_time'      // 有效期
    ];

    /**
     * 关联订单收货地址表
     */
    public function address()
    {
        return $this->hasOne("app\\common\\model\\store\\OrderAddressModel",'order_id','id');
    }

    /**
     * 订单商品列表
     * @return \think\model\relation\HasMany
     */
    public function goods()
    {
        return $this->hasMany("app\\common\\model\\store\\OrderGoodsModel",'order_id','id');
    }

    /**
     * 一对一关联用户表 (简单信息)
     * @return \think\model\relation\HasOne
     */
    public function user()
    {
        return $this->hasOne("app\\common\\model\\user\\UserModel", 'id', 'user_id')->field(['id','nickName', 'avatar'])->bind([
            'user_nickName' => 'nickName',
            'user_avatar' => 'avatar'
        ]);
    }

    /**
     * 一对一关联用户表 (详细)
     * @return \think\model\relation\HasOne
     */
    public function userDetail()
    {
        return $this->hasOne("app\\common\\model\\user\\UserModel", 'id', 'user_id');
    }

    /**
     * 关联订单收货地址表
     * @return \think\model\relation\HasOne
     */
    public function extract()
    {
        return $this->hasOne('app\\common\\model\\store\\OrderExtractModel','order_id','id');
    }

    public function extractShop()
    {
        return $this->belongsTo("app\\common\\model\\store\\ShopModel", 'id','shop_id');
    }



    /**
     * 配送类型修改器
     */
    public function getDeliveryTypeAttr($value)
    {
        return EnumFactory::instance('store.delivery_type')->getItem($value);
    }

    /**
     * 来源修改器
     */
    public function getOrderSourceAttr($value)
    {
        return EnumFactory::instance('store.order.source')->getItem($value);
    }

    /**
     * 状态修改器
     */
    public function getOrderStatusAttr($value)
    {
        return EnumFactory::instance('store.order.status')->getItem($value);
    }

    /**
     * 支付类型修改器
     */
    public function getPayTypeAttr($value)
    {
        return EnumFactory::instance('pay.type')->getItem($value);
    }

    /**
     * 付款状态修改器
     * @param $value
     * @return array
     */
    public function getPayStatusAttr($value)
    {
        return EnumFactory::instance('pay.status')->getItem($value);
    }

    /**
     * 发货状态修改器
     * @param $value
     * @return array
     */
    public function getDeliveryStatusAttr($value, $data)
    {
        $item = $this->getDeliveryTypeItem($value,$data['delivery_type']);
        return $item;
    }

    public function getDeliveryTypeItem($value,$deliveryType,$status = 'delivery'){
        $delivery = DeliveryTypeEnum::describe();
       return DeliveryTypeEnum::describe()[$deliveryType][$status][$value];
    }


    /**
     * 售后状态修改器
     */
    public function getRefundStatusAttr($value)
    {
        return EnumFactory::instance('store.order.refund_status')->getItem($value);
    }
    
    /**
     * 收货状态修改器
     * @param $value
     * @return array
     */
    public function getReceiptStatusAttr($value,$data)
    {
        $item = $this->getDeliveryTypeItem($value,$data['delivery_type'],'receipt');
        return $item;
    }

    /**
     * 订单状态文字描述
     */
    public function getStatusTextAttr($value, $data)
    {
        if(!isset($data['order_status'] )){
            return '已失效';
        }
        // 订单状态
        if ($data['order_status'] != StatusEnum::AFOOT) {
            return EnumFactory::instance('store.order.status')->getItem($data['order_status'])['name'];
        }
        // 付款状态
        if (!$data['pay_status']) {
            return '待付款';
        }
        $delivery = $this->getDeliveryTypeItem($data['delivery_status'],$data['delivery_type']);
        if (!$data['delivery_status']) {
            return '已付款，'.$delivery['name'] ?? '';
        }else{
            $receipt = $this->getDeliveryTypeItem($data['receipt_status'],$data['delivery_type'],'receipt');
            return ($data['delivery_type'] == 'express' ? $delivery['name'].',' :'').$receipt['name'];
        }
        return $value;
    }

    /**
     * 订单失效时间
     */
    public function getInvalidTimeAttr($value,$data){
        if (!empty($data) && $data['order_status'] == 2 && !$data['pay_status']) {
            return $data['create_time'] + (float)sysconf("store_order_close_time") * 3600 - time();
        }
        return 0;
    }

    /**
     * 支付时间修改器
     */
    public function getPayTimeAttr($value){
        if(!empty($value)){
            return formatDatetime($value);
        }
        return $value;
    }

    /**
     * 发货时间修改器
     */
    public function getDeliveryTimeAttr($value){
        if(!empty($value)){
            return formatDatetime($value);
        }
        return $value;
    }

    /**
     * 收货时间时间修改器
     */
    public function getReceiptTimeAttr($value){
        if(!empty($value)){
            return formatDatetime($value);
        }
        return $value;
    }
    
    /**
     * 改价金额（差价）
     * @param $value
     * @return array
     */
    public function getUpdatePriceAttr($value)
    {
        return [
            'symbol' => $value < 0 ? '-' : '+',
            'value' => sprintf('%.2f', abs($value))
        ];
    }

    /**
     * id搜索器
     */
    public function searchIdAttr($query, $value)
    {
        if (is_array($value)) {
            $query->whereIn('id', $value);
        } else {
            $query->where('id', $value);
        }
    }

    /**
     * user_id搜索器
     */
    public function searchUserIdAttr($query, $value)
    {
        if (is_array($value)) {
            $query->whereIn('user_id', $value);
        } else {
            $query->where('user_id', $value);
        }
    }

    /**
     * pay_status搜索器
     */
    public function searchPayStatusAttr($query, $value)
    {
        if (is_array($value)) {
            $query->whereIn('pay_status', $value);
        } else {
            $query->where('pay_status', $value);
        }
    }

    /**
     * order_status搜索器
     */
    public function searchOrderStatusAttr($query, $value)
    {   
        if (is_array($value)) {
            $query->whereIn('order_status', $value);
        } else {
            $query->where('order_status', $value);
        }
    }

    /**
     * delivery_status搜索器
     */
    public function searchDeliveryStatusAttr($query, $value)
    {
        if (is_array($value)) {
            $query->whereIn('delivery_status', $value);
        } else {
            $query->where('delivery_status', $value);
        }
    }

    /**
     * receipt_status搜索器
     */
    public function searchReceiptStatusAttr($query, $value)
    {
        if (is_array($value)) {
            $query->whereIn('receipt_status', $value);
        } else {
            $query->where('receipt_status', $value);
        }
    }

    /**
     * comment_status搜索器
     */
    public function searchCommentStatusAttr($query, $value)
    {
        if (is_array($value)) {
            $query->whereIn('comment_status', $value);
        } else {
            $query->where('comment_status', $value);
        }
    }

    /**
     * order_no搜索器
     */
    public function searchOrderNoAttr($query, $value)
    {
        if (is_array($value)) {
            $query->whereIn('order_no', $value);
        } else {
            $query->where('order_no', $value);
        }
    }

    /**
     * pay_type搜索器
     */
    public function searchPayTypeAttr($query, $value)
    {
        if (is_array($value)) {
            $query->whereIn('pay_type', $value);
        } else {
            $query->where('pay_type', $value);
        }
    }
}
